﻿using System;
using System.Configuration;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Linq;
using Owin;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using System.IO;

namespace ldhWebApiWF
{
    public partial class Form1 : Form
    {
        public IDisposable SignalR { get; set; }
        int httpPort = 8089;
        int readTimiePort = 8080;
        int debug = 1;
        int switchRealtime = 1;
        int filesv = 1;
        int filePort = 8099;
        internal int logRecords = 1000;
        bool isClose = true;
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            try
            {
                this.notifyIcon1.Text = ConfigurationManager.AppSettings["AppName"].ToString();
                this.Text = this.notifyIcon1.Text;
            } catch { }
            this.tb_path.ReadOnly = true;
            this.tb_path.Text = AppDomain.CurrentDomain.BaseDirectory;
            Load += Form1_Load;
        }

        void Form1_Load(object sender, EventArgs e)
        {
            Load -= Form1_Load;
            if (!int.TryParse(ConfigurationManager.AppSettings["http"], out httpPort))
            {
                MessageBox.Show("http端口读取错误，请检查config文件的端口配置。");
                return;
            }
            if (!int.TryParse(ConfigurationManager.AppSettings["file"], out filePort))
            {
                MessageBox.Show("file端口读取错误，请检查config文件的端口配置。");
                return;
            }
            if (!int.TryParse(ConfigurationManager.AppSettings["realtime"], out readTimiePort))
            {
                MessageBox.Show("RealTime端口读取错误，请检查config文件的端口配置。");
                return;
            }
            if (!int.TryParse(ConfigurationManager.AppSettings["debug"], out debug))
            {
                MessageBox.Show("Debug标识读取错误，请检查config文件的端口配置。");
                return;
            }
            if (!int.TryParse(ConfigurationManager.AppSettings["switchRealtime"], out switchRealtime))
            {
                MessageBox.Show("switchRealtime标识读取错误，请检查config文件的端口配置。");
                return;
            }
            if (!int.TryParse(ConfigurationManager.AppSettings["logRecords"], out logRecords))
            {
                MessageBox.Show("logRecords标识读取错误，请检查config文件的端口配置。");
                return;
            }
            if (!int.TryParse(ConfigurationManager.AppSettings["filesv"], out filesv))
            {
                MessageBox.Show("filesv标识读取错误，请检查config文件的端口配置。");
                return;
            }
            try
            {
                //读取ip限制白名单
                CheckIPMiddleware.IpWhitelist = ConfigurationManager.AppSettings["IpWhitelist"].Split(',').ToList();
                lb_msg.Items.Insert(0, ConfigurationManager.AppSettings["IpWhitelist"]);
            }
            catch
            {
                MessageBox.Show("读取ip限制白名单错误，请检查config文件的端口配置。");
                return;
            }
            if (debug == 1)
            {
                if (switchRealtime == 2 || switchRealtime == 1)
                {
                    Task.Run(() =>
                    {
                        string baseAddress = "http://localhost:" + httpPort;
                        WebApp.Start<WebApi>(url: baseAddress);
                        lb_msg.Items.Insert(0, "WebApi Server is run in " + baseAddress);
                    });
                }
                if (switchRealtime == 3 || switchRealtime == 1)
                {
                    string ServerURI = "http://localhost:" + readTimiePort;
                    Task.Run(() =>
                    {
                        SignalR = WebApp.Start<Startup_Signalr>(url: ServerURI);
                        lb_msg.Items.Insert(0, "Signalr Server is run in " + ServerURI);
                    });
                }
            }
            else
            {
                if (switchRealtime == 2 || switchRealtime == 1)
                {
                    Task.Run(() =>
                    {
                        string baseAddress = "http://*:" + httpPort;
                        var options = new StartOptions(baseAddress)
                        {
                            ServerFactory = "Microsoft.Owin.Host.HttpListener"
                        };
                        WebApp.Start<WebApi>(options);
                        lb_msg.Items.Insert(0, "WebApi Server is run in " + baseAddress);
                    });
                }
                if (switchRealtime == 3 || switchRealtime == 1)
                {
                    Task.Run(() =>
                    {
                        string ServerURI = "http://*:" + readTimiePort;
                        var options = new StartOptions(ServerURI)
                        {
                            ServerFactory = "Microsoft.Owin.Host.HttpListener"
                        };
                        SignalR = WebApp.Start<Startup_Signalr>(options);
                        lb_msg.Items.Insert(0, "Signalr Server is run in " + ServerURI);
                    });
                }
                if (filesv == 2)
                {
                    Task.Run(() =>
                    {
                        var path = AppDomain.CurrentDomain.BaseDirectory + "uploads\\";
                        var fileurl = "http://*:" + +filePort;
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        var fileSystem = new PhysicalFileSystem(path);
                        var ops = new FileServerOptions();
                        ops.EnableDirectoryBrowsing = true;
                        ops.FileSystem = fileSystem;
                        //ops.StaticFileOptions.ContentTypeProvider = new CustomContentTypeProvider();
                        WebApp.Start(fileurl, builder => builder.UseFileServer(ops));
                        lb_msg.Items.Insert(0, "File Server is run in " + fileurl);
                    });
                }
            }
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x0010 && isClose)
            {
                Hide();
                return;
            }

            base.WndProc(ref m);
        }

        private void 显示程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Show();
        }

        private void 隐藏程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Hide();
        }

        private void 退出程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            isClose = false;
            Close();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Show();
        }

    }
}
